package me.jessyan.mvparms.demo.login.mvp.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rmyh.yanxun.R;
import com.rmyh.yanxun.model.bean.LoginInfo;
import com.rmyh.yanxun.model.bean.TopResponse;
import com.rmyh.yanxun.ui.activity.BaseActivity;
import com.rmyh.yanxun.ui.activity.home.HomeActivity;
import com.rmyh.yanxun.utils.Constant;
import com.rmyh.yanxun.utils.NetWorkUtils;
import com.rmyh.yanxun.utils.RetorfitUtil;
import com.rmyh.yanxun.utils.SharedPreUtils;
import com.rmyh.yanxun.utils.ToastUtils;
import com.rmyh.yanxun.view.SelfDialog;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 2017/4/11 11:12
 */
public class LoginActivity extends BaseActivity implements View.OnFocusChangeListener, View.OnClickListener {

    @InjectView(R.id.login_username)
    EditText loginUsername;
    @InjectView(R.id.login_username_clear)
    ImageView loginUsernameClear;
    @InjectView(R.id.login_password)
    EditText loginPassword;
    @InjectView(R.id.login_password_clear)
    ImageView loginPasswordClear;
    @InjectView(R.id.login_findpwd)
    TextView loginFindpwd;
    @InjectView(R.id.login_btn_login)
    Button loginBtnLogin;
    @InjectView(R.id.login_callphone)
    TextView loginCallphone;
    @InjectView(R.id.loading_login)
    ProgressBar loadingLogin;
    private View view1;
    private TextView phone1;
    private TextView phone2;
    private Dialog builder;
    private static final String message = "请在电脑端登录";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        RxPermissions rxPermissions = new RxPermissions(LoginActivity.this);
        //分别申请多个权限时，使用requestEach
        rxPermissions.requestEach(Manifest.permission.CALL_PHONE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA).subscribe(new Action1<Permission>() {
            @Override
            public void call(Permission permission) {
                if (permission.name.equals(Manifest.permission.CALL_PHONE)) {
                    if (permission.granted == false) {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.CALL_PHONE, false);
                    } else {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.CALL_PHONE, true);
                    }
                }
                if (permission.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (permission.granted == false) {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.WRITE_EXTERNAL_STORAGE, false);
                    } else {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.WRITE_EXTERNAL_STORAGE, true);
                    }
                }
                if (permission.name.equals(Manifest.permission.CAMERA)) {
                    if (permission.granted == false) {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.CAMERA, false);
                    } else {
                        SharedPreUtils.putBoolean(LoginActivity.this, Constant.CAMERA, true);
                    }
                }
            }
        });

        TransformationMethod method = PasswordTransformationMethod.getInstance();
        loginPassword.setTransformationMethod(method);

        //监视输入框的变化
        if (loginUsername != null && loginPassword != null) {
            loginUsername.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    String phoneOther = loginUsername.getText().toString().trim();
                    if (!TextUtils.isEmpty(phoneOther)) {
                        loginUsernameClear.setVisibility(View.VISIBLE);
                    } else {
                        loginUsernameClear.setVisibility(View.GONE);
                    }
                }
            });
            loginPassword.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    String phoneOther = loginUsername.getText().toString().trim();
                    if (!TextUtils.isEmpty(phoneOther)) {
                        loginPasswordClear.setVisibility(View.VISIBLE);
                    } else {
                        loginPasswordClear.setVisibility(View.GONE);
                    }
                }
            });
            loginUsername.setOnFocusChangeListener(this);
            loginPassword.setOnFocusChangeListener(this);
        }

    }

    @OnClick({R.id.login_username_clear, R.id.login_password_clear, R.id.login_findpwd, R.id.login_btn_login, R.id.login_callphone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_username_clear:
                loginUsername.setText("");
                break;
            case R.id.login_password_clear:
                loginPassword.setText("");
                break;
            case R.id.login_findpwd:
                //跳转找回密码界面
                Intent intent = new Intent(LoginActivity.this, FindPwdOne.class);
                startActivity(intent);
                break;
            case R.id.login_btn_login:
                loadingLogin.setVisibility(View.VISIBLE);
                String username = loginUsername.getText().toString().trim();
                String pwd = loginPassword.getText().toString().trim();
                if (checkData(username, pwd)) {
                    RetorfitUtil.getInstance().create().getLoginData(username, pwd)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            //类型转换   变成你想要的类型
                            .flatMap(new Func1<TopResponse<LoginInfo>, Observable<LoginInfo>>() {
                                @Override
                                public Observable<LoginInfo> call(TopResponse<LoginInfo> loginInfoTopResponse) {
                                    if ("200".equals(loginInfoTopResponse.getStatus())) {
                                        return Observable.just(loginInfoTopResponse.getData());
                                    } else if ("203".equals(loginInfoTopResponse.getStatus())) {
                                        String s = loginInfoTopResponse.getStatus() + loginInfoTopResponse.getInfo();
                                        return Observable.error(new Throwable(s));
                                    } else {
                                        return Observable.error(new Throwable(loginInfoTopResponse.getInfo()));
                                    }
                                }
                            })
                            .subscribe(new Subscriber<LoginInfo>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    if (NetWorkUtils.isNetConnected(LoginActivity.this)) {
                                        if ("203".equals(e.getMessage().substring(0, 3))) {
                                            final SelfDialog selfDialog = new SelfDialog(LoginActivity.this);
                                            View inflate = LayoutInflater.from(LoginActivity.this).inflate(R.layout.dialog_play, null, false);
                                            TextView dialog_play_title = (TextView) inflate.findViewById(R.id.dialog_play_title);
                                            Button dialog_play_confirm = (Button) inflate.findViewById(R.id.dialog_play_confirm);
                                            Button dialog_play_canle = (Button) inflate.findViewById(R.id.dialog_play_canle);
                                            dialog_play_canle.setVisibility(View.GONE);
                                            dialog_play_title.setText(e.getMessage().substring(3));
                                            dialog_play_confirm.setText("确定");
                                            selfDialog.getLayoutId(inflate);
                                            dialog_play_confirm.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    selfDialog.dismiss();
                                                }
                                            });
                                            selfDialog.show();
                                        } else {
                                            ToastUtils.showLongToast(e.getMessage());
                                        }
                                    } else {
                                        ToastUtils.showToast("网络不可用，请检查网络！");
                                    }
                                    loadingLogin.setVisibility(View.GONE);
                                }

                                @Override
                                public void onNext(LoginInfo loginInfo) {
                                    loadingLogin.setVisibility(View.GONE);
                                    SharedPreUtils.putString(LoginActivity.this, Constant.TOKEN, loginInfo.getToken());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.PHOTO, loginInfo.getPhoto());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.USERNAME, loginInfo.getUsername());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.REALNAME, loginInfo.getRealName());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.ISUSEER, loginInfo.getIsUser());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.ISYX, loginInfo.getIsYx());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.IsJw, loginInfo.getIsJw());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.isBjedu, loginInfo.getIsBjedu());
                                    SharedPreUtils.putString(LoginActivity.this, Constant.IsRegister, loginInfo.getIsRegister());
                                    Intent intent1 = new Intent(LoginActivity.this, HomeActivity.class);
                                    startActivity(intent1);
                                    finish();
                                }
                            });
                }
                break;
            case R.id.login_callphone:
                if (!SharedPreUtils.getBoolean(LoginActivity.this, Constant.CALL_PHONE, false)) {
                    ToastUtils.showToast("您没有授予打电话权限，请重新登录根据提示授予！！");
                    return;
                }
                this.builder = new Dialog(this);
                this.builder.setTitle("请选择要拨打的电话");
                view1 = LayoutInflater.from(this).inflate(R.layout.activity_login_dialog, null, false);
                phone1 = (TextView) view1.findViewById(R.id.phone1);
                phone2 = (TextView) view1.findViewById(R.id.phone2);
                phone1.setOnClickListener(this);
                phone2.setOnClickListener(this);
                this.builder.setContentView(view1);
                this.builder.show();
                break;
            default:
                break;
        }
    }

    //检查输入合法性

    private boolean checkData(String username, String pwd) {
        if (TextUtils.isEmpty(username) || username.length() == 0) {
            Toast.makeText(this, "请填写用户名", Toast.LENGTH_SHORT).show();
            loadingLogin.setVisibility(View.GONE);
            return false;
        }
        if (TextUtils.isEmpty(pwd) || pwd.length() == 0) {
            Toast.makeText(this, "请填写密码", Toast.LENGTH_SHORT).show();
            loadingLogin.setVisibility(View.GONE);
            return false;
        }
        return true;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.login_username:
                String username = loginUsername.getText().toString();
                if (!TextUtils.isEmpty(username) && hasFocus) {
                    loginUsernameClear.setVisibility(View.VISIBLE);
                } else {
                    loginUsernameClear.setVisibility(View.GONE);
                }
                break;
            case R.id.login_password:
                String password = loginPassword.getText().toString();
                if (!TextUtils.isEmpty(password) && hasFocus) {
                    loginPasswordClear.setVisibility(View.VISIBLE);
                } else {
                    loginPasswordClear.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    //点击拨打电话
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.phone1:
                builder.dismiss();
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone1.getText()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.phone2:
                builder.dismiss();
                Intent intent1 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone2.getText()));
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent1);
                break;
            default:
                break;
        }
    }
}
